package com.atech.ace.business;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.ejb.Stateless;

import com.atech.ace.business.client.OrderAdministrationRemote;
import com.atech.ace.dao.CategoryHome;
import com.atech.ace.dao.OrderHome;
import com.atech.ace.dao.OrderitemHome;
import com.atech.ace.dao.ProductHome;
import com.atech.ace.entity.Category;
import com.atech.ace.entity.Order;
import com.atech.ace.entity.Orderitem;
import com.atech.ace.entity.Product;
import com.atech.ace.entity.User;

/**
 * Session Bean implementation class OrderAdministration
 */
@Stateless
public class OrderAdministration implements OrderAdministrationRemote, OrderAdministrationLocal {

    /**
     * Default constructor. 
     */
    public OrderAdministration() {
        // TODO Auto-generated constructor stub
    }
    
    public void createOrder(Order order)
    {
    	OrderHome orderManager = new OrderHome();
    	OrderitemHome orderitemManager = new OrderitemHome();
    	orderManager.persist(order);
    	Set orderItems = order.getOrderitems();
    	Iterator i = orderItems.iterator();
    	while(i.hasNext()){
    		Orderitem item = ( Orderitem) i.next();
    		item.setOrder(order);
    		orderitemManager.persist(item);    		
    	}
    }
    
    public List getOrders(String username)
    {
    	Order o = new Order();
    	User u = new User();
    	o.setUser(u);
    	OrderHome orderManager = new OrderHome();
    	List orders = orderManager.findByExample(o);
    	return orders;
    }
    
    public List getCategories()
    {
    	CategoryHome categoryManager = new CategoryHome();
    	List categories = categoryManager.findAll();
    	System.out.println("returning: " + categories.size());
    	return categories;
    }
    public Map getCatalog()
    {
    	Map catalog = new LinkedHashMap();
    	
    	List categories = getCategories();
    	Iterator i = categories.iterator();
    	while(i.hasNext())
    	{
    		Category c = ( Category ) i.next();
    		List products = getProducts(c);
    		catalog.put(c.getCategoryId(), products);    		
    	}
    	return catalog;
    }
    
    public List getProducts(Category category)
    {
    	ProductHome productManager = new ProductHome();
    	Product p = new Product();
    	p.setCategory(category);
    	List products = productManager.findByExample(p);
    	return products;
    	
    }
    
    public Map getAllProducts()
    {
    	ProductHome productManager = new ProductHome();
    	return productManager.findAll();
    }

}
